package cn.itcast.tools.Timer_计时器;

import java.text.Format;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;

//https://www.cnblogs.com/jinshiyill/p/5252732.html
class MyTask extends TimerTask{

    private String aa = "";
    MyTask(String aa){
        this.aa = aa;
    }

    public void run() {
        Format format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss:SSS");
        System.out.println("当前时间：" + format.format(new Date()));
        System.out.println(this.aa);
    }

}

public class Demo {

    public static void main(String[] args) {
        System.out.println("================");
        Timer timer = new Timer();
        //timer.schedule(new MyTask(), 1000, 1000);  //1秒后执行，并且每隔1000毫秒重复执行
        //注意for循环里面的延迟在单个循环里面是不起作用的
        for(int i = 0; i < 10; ++i)
            timer.schedule(new MyTask("this is a test"), 3000);


        try {
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        timer.cancel();  //终止计时器，放弃所有已安排的任务
        timer.purge();  //释放内存
    }

}
